/**
 * 分页组件
 * @author hxy
 */
Package("shihua.common.Pagination");
shihua.common.Pagination = function(obj, options,staticTotalRecord){
	var pageNumber = 1;//当前页数
	var perPage = 10;//每页数据条数
	var totalRecord = 0;//总记录数/行数
	var totalPage = 0;//总页数
	var startRecord = 0;//当前页第一条数据的记录数/行数
	var endRecord = 0;//当前页最后数据的记录数/行数
	var btnFirst;//首页对象
	var btnPrev;//上一页对象
	var btnList;//页数集合对象
	var btnNext;//下一页对象
	var btnLast;//末页对象
	var btnGo;//GO按钮对象
	var btn;//按钮对象（首页 + 上一页 + 末页 + 下一页 + GO）
	var oPagerNumber;//当前页对象
	var oTotalPage;//总行数对象
	var oStartRecord;//开始记录数对象
	var oEndRecord;//结束记录数对象
	var oTotalRecord;//总记录数对象
	var oSelectperPage;//选择每页行数对象
	var fisrtGetRemoteData=true;
	var cacheObj = $("<div></div>");
	/**
	 *  初始化方法
	 */
	this.getPageNumber=function(){
		return pageNumber;
	};
	this.getPerPage=function(){
		return perPage;
	};
	(function init(){
		
		if (options != "static") {
			if (!options.proxyUrl) {
				alert("request url is not exist!");
				return;
			}
			if (!jQuery.isFunction(options.success)) {
				alert("back function is not exist!");
				return;
			}
		}
		
		
		pageNumber = options.pageNumber ? options.pageNumber : 1;
		perPage = options.perPage ? options.perPage : 10;
		
		btnFirst = obj.find("*[key='btnFirst']");
		btnPrev = obj.find("*[key='btnPrev']");
		btnList = obj.find("*[key='btnList']");
		btnNext = obj.find("*[key='btnNext']");
		btnLast = obj.find("*[key='btnLast']");
		btnGo = obj.find("*[key='btnGo']");
		btn = obj.find("*[key='btnFirst'],*[key='btnPrev'],*[key='btnNext'],*[key='btnLast'],*[key='btnGo']");
		oPagerNumber = obj.find("*[key='oPagerNumber']");
		oTotalPage = obj.find("*[key='oTotalPage']");
		oStartRecord = obj.find("*[key='oStartRecord']");
		oEndRecord = obj.find("*[key='oEndRecord']");
		oTotalRecord = obj.find("*[key='oTotalRecord']");
		oSelectperPage = obj.find("*[key='oSelectperPage']");
		if (options == "static") {
			pageNumber = (obj.attr("pageNumber")||1)*1;
			perPage    = obj.attr("perPage")*1;
			calculate(obj.attr("totalRecord")*1);
			refresh();
		}
		else {
			getRemoteData();
		}
		setEvent();
		
	})();
	

	/**
	 * 获取远程数据
	 */
	function getRemoteData(){
		if (options == "static") {
			if(obj.attr("backfunction")){
				eval(obj.attr("backfunction")+"("+pageNumber+",obj)");
			}else{
				var url = location.href;
				var pageNumberName = obj.attr("pageNumberName")||"pageNumber";
				if(url.indexOf(pageNumberName)>-1){
					url =url.replace(new RegExp(pageNumberName+"=(\\d*)","g"),pageNumberName+"="+pageNumber);
				}else{
					if(url.indexOf("?")>-1){
						url+="&"+pageNumberName+"="+pageNumber;
					}else{
						url+="?"+pageNumberName+"="+pageNumber;
					}
				}
				
				if(obj.attr("currPageIndex")){
					var _name  = "currPageIndex";
					var _value = obj.attr("currPageIndex");
					if(url.indexOf(_name)>-1){
						url =url.replace(new RegExp(_name+"=(\\d*)","g"),_name+"="+_value);
					}else{
						if(url.indexOf("?")>-1){
							url+="&"+_name+"="+_value;
						}else{
							url+="?"+_name+"="+_value;
						}
					}
				}
				location.href = url;
			}			
		}else if (staticTotalRecord != null && fisrtGetRemoteData) {
			calculate(staticTotalRecord);
			refresh();
			fisrtGetRemoteData=false;
		} else {
			var key = pageNumber + '_' + perPage;
			var curData = cacheObj.data(key);
			if (false) {
				success(curData);
			} else {
				var data = jQuery.extend(options.parameters, {
					pagerNumber: pageNumber,
					perPage: perPage
				});
				jQuery.ajax({
					type: "POST",
					url: options.proxyUrl,
					data: data,
					dataType: "json",
					timeout: 30000,
					beforeSend: startLoad,
					complete: overLoad,
					success:  function(json){
						cacheObj.data(key , json);
						success(json);
					},
					error: error,
					global: false,
					cache: false
				});
			}
		}
	}
	
	/**
	 * 获取远程数据成功
	 * @param {Object} json
	 */
	function success(json){
		if (null != json && json.ret == 0) {
			calculate(json.totalRecord);
			refresh();
			options.success(json);
		} else {
			options.success(json);
		}
	}
	
	/**
	 * 获取远程数据失败
	 */
	function error(){
		if (jQuery.isFunction(options.error)) {
			options.error();
		} else {
			alert("Request failed or timed out, please try again later!");
		}
	}
	
	/**
	 * 设置分页组件事件及样式
	 */
	function setEvent(){
	
		btnFirst.unbind().hover(function(){
			setClass(this, "btnFirst_hover", pageNumber > 1);
		}, function(){
			setClass(this, "btnFirst", pageNumber > 1);
		}).mousedown(function(){
			setClass(this, "btnFirst_press", pageNumber > 1);
		}).click(function(){
			if (pageNumber > 1) {
				pageNumber = 1;
				getRemoteData();
			}
			return false;
		});
		
		btnPrev.unbind().hover(function(){
			setClass(this, "btnPrev_hover", pageNumber > 1);
		}, function(){
			setClass(this, "btnPrev", pageNumber > 1);
		}).mousedown(function(){
			setClass(this, "btnPrev_press", pageNumber > 1);
		}).click(function(){
			if (pageNumber > 1) {
				pageNumber -= 1;
				getRemoteData();
			}
			return false;
		});
		
		btnNext.unbind().hover(function(){
			setClass(this, "btnNext_hover", pageNumber < totalPage);
		}, function(){
			setClass(this, "btnNext", pageNumber < totalPage);
		}).mousedown(function(){
			setClass(this, "btnNext_press", pageNumber < totalPage);
		}).click(function(){
			if (pageNumber < totalPage) {
				pageNumber += 1;
				getRemoteData();
			}
			return false;
		});
		
		btnLast.unbind().hover(function(){
			setClass(this, "btnLast_hover", pageNumber < totalPage);
		}, function(){
			setClass(this, "btnLast", pageNumber < totalPage);
		}).mousedown(function(){
			setClass(this, "btnLast_press", pageNumber < totalPage);
		}).click(function(){
			if (pageNumber < totalPage) {
				pageNumber = totalPage;
				getRemoteData();
			}
			return false;
		});
		
		btnGo.unbind().hover(function(){
			setClass(this, "btnGo_hover", totalPage > 1);
		}, function(){
			setClass(this, "btnGo", totalPage > 1);
		}).mousedown(function(){
			setClass(this, "btnGo_press", totalPage > 1);
		}).click(function(){
			if (totalPage > 1) {
				checkPerPage();
			}
			return false;
		});
		
		
		oPagerNumber.unbind().keyup(function(){
			oPagerNumber.val(jQuery(this).val());
			
		}).blur(function(event){
			if (totalPage > 1) {
				
					checkPerPage();
				
			}
		});
		
		oSelectperPage.unbind().change(function(){
			perPage = parseInt(jQuery(this).val());
			pageNumber = 1;
			totalPage = Math.ceil(totalRecord / perPage);
			getRemoteData();
		});
		
		btnList.addClass("btnList");
		oPagerNumber.addClass("oPagerNumber");
		oTotalPage.addClass("oTotalPage");
		oStartRecord.addClass("oStartRecord");
		oEndRecord.addClass("oEndRecord");
		oTotalRecord.addClass("oTotalRecord");
		oSelectperPage.addClass("oSelectperPage");
	}
	
	/**
	 * 检查用户输入页数方法
	 */
	function checkPerPage(){
		var targetPage = jQuery.trim(oPagerNumber.val());
		if (targetPage != '' && /^\d+$/.test(targetPage) == true && targetPage > 0 && targetPage <= totalPage) {
			if (pageNumber == targetPage) {
				return false;
			}
			pageNumber = parseInt(targetPage);
			getRemoteData();
		} else {
			art.dialog.tips("\u8BF7\u8F93\u5165\u4ECB\u4E8E0\u548C" + (parseInt(totalPage) + 1) + "\u4E4B\u95F4\u7684\u6570\u5B57\uFF01");
		}
	}
	
	/**
	 * 根据总记录数/行数，和每页数据条数，计算分页
	 */
	function calculate(_totalRecord){
		totalRecord = _totalRecord;
		totalPage = Math.ceil(totalRecord / perPage);
		if(_totalRecord==0){
			startRecord = 0;
		}else{
			startRecord = (pageNumber - 1) * perPage + 1;
		}
		if(totalPage<pageNumber){
			pageNumber=totalPage;
		}
		if(totalPage<=1){
			obj.hide();
		}else{
			obj.show();
		}
		endRecord = Math.min(pageNumber * perPage, totalRecord);
	}
	
	/**
	 * 刷新分页组件
	 */
	function refresh(){
		oPagerNumber.val(pageNumber);
		oTotalPage.html(totalPage);
		oStartRecord.html(startRecord);
		oEndRecord.html(endRecord);
		oTotalRecord.html(totalRecord);
		
		btn.removeClass();
		if(totalPage <= 1){
			btnFirst.addClass("btnFirst_disabled");
			btnPrev.addClass("btnPrev_disabled");
			btnNext.addClass("btnNext_disabled");
			btnLast.addClass("btnLast_disabled");
		}else if (pageNumber == 1) {
			btnFirst.addClass("btnFirst_disabled");
			btnPrev.addClass("btnPrev_disabled");
			btnNext.addClass("btnNext");
			btnLast.addClass("btnLast");
		}else if (pageNumber == totalPage) {
			btnFirst.addClass("btnFirst");
			btnPrev.addClass("btnPrev");
			btnNext.addClass("btnNext_disabled");
			btnLast.addClass("btnLast_disabled");
		} else {
			btnFirst.addClass("btnFirst");
			btnPrev.addClass("btnPrev");
			btnNext.addClass("btnNext");
			btnLast.addClass("btnLast");
		}
		
		if (totalPage > 1) {
			btnGo.addClass("btnGo");
			oPagerNumber.removeAttr("disabled");
		} else {
			btnGo.addClass("btnGo_disabled");
			oPagerNumber.attr("disabled", "true");
		}
		
		jQuery.each(oSelectperPage.children(), function(i, n){
			if (n.value == perPage) {
				this.selected = true;
			}
		});
		makeBtnList();
	}
	
	/**
	 * 计算页数按钮
	 */
	function makeBtnList(){
		btnList.empty();
		for (var i = 1; i <= totalPage; i++) {
			switch (i)
			{
				case 1:
				case 2:
				case pageNumber - 2:
				case pageNumber - 1:
				case pageNumber:
				case pageNumber + 1:
				case pageNumber + 2:
				case totalPage - 1:
				case totalPage:
					buildBtnList(i);
					break;
				case pageNumber - 3:
				case pageNumber + 3:
					buildBtnList(0);
					break;
			}
		}
	}
	
	/**
	 * 生成页数按钮
	 * @param {Object} pageNum
	 */
	function buildBtnList(pageNum){
		if (pageNum == 0) {
			btnList.append(jQuery("<div/>").addClass("btnPoint").html('...'));
			return true;
		}
		
		btnList.each(function(i, n){
			var btni = jQuery("<div/>").attr("id", "btnList" + pageNum).html(pageNum);
			if (pageNum != pageNumber) {
				btni.removeClass().addClass("btnPage").hover(function(){
					setClass(this, "btnPage_hover", true);
				}, function(){
					setClass(this, "btnPage", true);
				}).mousedown(function(){
					setClass(this, "btnPage_press", true);
				}).click(function(){
					pageNumber = parseInt(jQuery.trim(jQuery(this).html()));
					getRemoteData();
					return false;
				});
			}
			else {
				btni.removeClass().addClass("btnPage_current");
			}
			jQuery(this).append(btni);
		});
	}
	
	/**
	 * 设置样式
	 * @param {Object} obj
	 * @param {Object} _class
	 */
	function setClass(obj, _class, condition){
		if (condition) {
			jQuery(obj).removeClass().addClass(_class);
		}
	}
	
	/**
	 * 发送获取数据请求前的方法
	 */
	function startLoad(){
		if (jQuery.isFunction(options.startLoad)) {
			options.startLoad();
		} else {
			//暂时不实现
		}
	}
	
	/**
	 * 发送获取数据请求完成的方法，包括请求失败
	 */
	function overLoad(){
		if (jQuery.isFunction(options.overLoad)) {
			options.overLoad();
		} else {
			//暂时不实现
		}
	}
};
shihua.common.Pagination.create = function(obj, options,staticparam){
	return new shihua.common.Pagination(obj, options,staticparam);
};
